package com.ozo.easy.common.file;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.ozo.easy.common.config.OzoProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 文件存储
 *
 * @author ozo
 * @date 2024-05-13
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class FileServiceImpl implements IFileService {

    private final OzoProperties ozoProperties;

    @Override
    public void createDirectory(String directoryName) {
        Path path = Paths.get(ozoProperties.getUploadDir() + File.separator + directoryName);
        try {
            Files.createDirectories(path);
        } catch (IOException e) {
            throw new RuntimeException("Could not create directory: " + directoryName, e);
        }
    }

    @Override
    public void deleteDirectory(String directoryName) {
        Path path = Paths.get(ozoProperties.getUploadDir() + File.separator + directoryName);
        try {
            Files.deleteIfExists(path);
        } catch (IOException e) {
            throw new RuntimeException("Could not delete directory: " + directoryName, e);
        }
    }

    @Override
    public String uploadFile(MultipartFile file, String directoryName) {
        // 文件名
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID() + suffix;

        String relativePath = StrUtil.isNotBlank(directoryName) ? directoryName + File.separator + fileName : fileName;
        try {
            File dest = new File(ozoProperties.getUploadDir() + File.separator + relativePath);
            File directory = dest.getParentFile();
            if (!directory.exists()) {
                directory.mkdirs();
            }
            file.transferTo(dest);
        } catch (IOException e) {
            throw new RuntimeException("Could not upload file: " + file.getOriginalFilename(), e);
        }
        return relativePath;
    }

    @Override
    public void deleteFile(String filePath) {
        Path path = Paths.get(ozoProperties.getUploadDir() + File.separator + filePath);
        try {
            Files.deleteIfExists(path);
        } catch (IOException e) {
            throw new RuntimeException("Could not delete file: " + filePath, e);
        }
    }

    @Override
    public byte[] downloadFile(String filePath) {
        Path path = Paths.get(ozoProperties.getUploadDir() + File.separator + filePath);
        try {
            return Files.readAllBytes(path);
        } catch (IOException e) {
            throw new RuntimeException("Could not download file: " + filePath, e);
        }
    }

}